// 购物车状态
import {
  getNewCartGoods,
  reqMergeLocalCart,
  reqFindCartList,
  reqInsertCart,
  reqDeleteCart,
  reqUpdateCartSku,
  reqCheckAllCart
} from '@/api/cart'

export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  mutations: {
    // 点击购物车添加商品
    updateList (state, list) {
      const index = state.list.findIndex((item) => item.skuId === list.skuId)
      if (index !== -1) {
        state.list[index].count += list.count
      } else {
        state.list.push(list)
        console.log(state.list, '0000kk')
      }
    },

    // 删除商品
    delListInfo (state, skuId) {
      const index = state.list.findIndex((item) => item.skuId === skuId)
      state.list.splice(index, 1)
    },

    // 失效商品处理
    updateFailure (state, list) {
      // state.list = {}
      Object.assign(state.list, list)
    },

    // 更新单选框
    updateRadio (state, { selected, skuId }) {
      const index = state.list.findIndex((item) => item.skuId === skuId)
      index && (state.list[index].selected = selected)
    },

    // 更新单选框
    updateSeleced (state, selected) {
      state.list.forEach((item) => {
        item.selected = selected
      })
    },

    // 商品数量的改变
    updateChangeCount (state, { count, skuId }) {
      const index = state.list.findIndex((item) => item.skuId === skuId)
      state.list[index].count = count
    }
  },
  actions: {
    // 点击添加购物车
    setList (context, objList) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录过
          const { count, skuId } = objList
          await reqInsertCart({ skuId, count })
          await context.dispatch('failureGoods')
          resolve()
        } else {
          // 没有登录过
          context.commit('updateList', objList)
          resolve()
        }
      })
    },

    // 失效商品处理
    failureGoods (context) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录过
          // console.log('已登录，发请求 - 异步操作')
          const res = await reqFindCartList()
          context.commit('updateFailure', res.result)
          resolve()
        } else {
          // 没有登录过
          const skuIdArr = context.state.list.map((item) =>
            getNewCartGoods(item.skuId)
          )
          const res = Promise.all(skuIdArr).then((res) => {
            return res.map((item) => {
              const skuObj = {}
              Object.keys(item.result).forEach((i) => {
                if (item.result[i]) {
                  skuObj[i] = item.result[i]
                }
              })
              return skuObj
            })
          })
          context.commit('updateFailure', res)
          resolve()
        }
      })
    },

    // 更新单选按钮
    changeRadio (context, { selected, skuId }) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录过
          await reqUpdateCartSku({
            skuId,
            selected
          })
          context.dispatch('failureGoods')
          resolve()
        } else {
          // 没有登录过
          context.commit('updateRadio', { selected, skuId })
          resolve()
        }
      })
    },

    // 更新全选按钮
    selecedAll (context, selected) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录过
          const skuIds = context.getters.reckonValidList.map(item => item.skuId)
          await reqCheckAllCart({ selected, ids: skuIds })
          await context.dispatch('failureGoods')
          resolve()
        } else {
          // 没有登录过
          context.commit('updateSeleced', selected)
          resolve()
        }
      })
    },

    // 删除商品
    delGoods (context, goods) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录过
          await reqDeleteCart([goods.skuId])
          console.log(goods.skuId, '000ikk')
          await context.dispatch('failureGoods')
        } else {
          // 没有登录过
          context.commit('delListInfo', goods.skuId)
          resolve()
        }
      })
    },

    // 商品数量的改变
    changeCount (context, obj) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录过
          console.log(obj)
          await reqUpdateCartSku({
            skuId: obj.skuId,
            count: obj.count
          })
          context.dispatch('failureGoods')
          resolve()
        } else {
          // 没有登录过
          context.commit('updateChangeCount', obj)
          resolve()
        }
      })
    },

    // 合并本地购物车 actions
    async asyncMergeLocalCart (context) {
      // 存储token后调用本地接口同步
      const cartList = context.state.list.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await reqMergeLocalCart(cartList)
      // 合并成功后，从后端获取最新购物车列表替换本地
      await context.dispatch('failureGoods')
    }
  },
  getters: {
    // 计算出有效商品列表
    reckonValidList (state) {
      return state.list.filter((item) => item.stock > 0 && item.isEffective)
    },

    // 计算出有效商品的数量
    reckonListCount (state, getters) {
      return getters.reckonValidList.reduce((old, newV) => old + newV.count, 0)
    },

    // 计算出有效商品的总价
    reckonListPrice (state, getters) {
      return getters.reckonValidList.reduce(
        (old, newV) => old + newV.count * newV.nowPrice,
        0
      )
    },

    // 计算出失效商品列表
    failureValidList (state, getters) {
      return state.list.filter((item) => !(item.stock > 0 && item.isEffective))
    },

    // 计算出选中的商品
    reckonSelectList (state, getters) {
      return state.list.filter((item) => item.selected)
    },

    // 计算出选中的商品的价格
    reckonSelectPrice (state, getters) {
      return getters.reckonSelectList.reduce(
        (old, newV) => old + newV.count * newV.nowPrice,
        0
      )
    },

    // 计算出是否全选
    isSelectedAll (state, getters) {
      return getters.reckonValidList.every((item) => item.selected)
    }
  }
}
